package com.heima.wemedia.service.impl;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    private static final List<String> IMAGE_TYPE_LIST= Arrays.asList("jpg","png","bmg","gif","jpeg");

    /**
     * 素材上传
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ResponseResult upload(MultipartFile file) {
        //获取userId
        WmUser wmUser = WmThreadLocalUtil.getUser();
        Integer userId = wmUser.getId();
        //1.判断文件的合法性
        //1.1文件不能为空
        if (file.isEmpty() || file.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.2文件必须是图片
        try {
            //基于输入流获取原始的文件类型（）
            String type = FileTypeUtil.getType(file.getInputStream());
            if (!IMAGE_TYPE_LIST.contains(type)){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"不是图片");
            }

            //2.生成唯一文件名:前缀名+后缀名
            //获取前缀名
            String filePrefixName = IdUtil.fastSimpleUUID();//文件前缀名（绝对唯一）
            //连接符
            String filePostfixName = ".";
            //获取文件全名
            String fileName =filePrefixName+filePostfixName+type;
            //3.上传文件到Minio
            String url = fileStorageService.uploadImgFile(null, fileName, file.getInputStream());
            System.out.println(url);
            //4.保存素材
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(url);
            wmMaterial.setUserId(userId);
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            boolean save = this.save(wmMaterial);
            System.out.println("图片是否存入成功:"+save);
        } catch (IOException e) {
            e.printStackTrace();

            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"上传出现问题");
        }
        //TODO

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
       //TODO

        //1.设置分页参数的默认值
        dto.checkParam();
        //2.执行分页条件查询
        IPage<WmMaterial> page =new Page<>(dto.getPage(),dto.getSize());
        this.page(page, Wrappers
                .<WmMaterial>lambdaQuery()
                //根据id查询
                .eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId())
                //根据iscollection是否收藏 0:没有 1:有
                .eq(dto.getIsCollection()>0,WmMaterial::getIsCollection,dto.getIsCollection())
                //根据时间倒序排序
                .orderByDesc(WmMaterial::getCreatedTime)
        );
        //3.封装拼接分页结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;

        /*LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        List<WmMaterial> wmMaterials = this.list(queryWrapper);
        ResponseResult page=new PageResponseResult(dto.getPage(), dto.getSize(),wmMaterials.size());
        page.setData(wmMaterials);
        page.setErrorMessage("操作成功");
        return page;*/
    }

    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(Integer id) {
        //TODO根据id删除素材
        //1.判断参数的合法性
        if (id ==null ||id<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断数据是否存在

        Integer count = this.lambdaQuery().eq(WmMaterial::getId, id).count();
        if (count<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.判断素材是否被引用 select count(*) from wm_news_material where material_id = ?
        Integer countRelation = wmNewsMaterialService.lambdaQuery().eq(WmNewsMaterial::getMaterialId, id).count();
        if (countRelation>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"素材被引用无法删除");
        }
        //4.删除minio中的素材
        WmMaterial wmMaterial = this.getById(id);
        fileStorageService.delete(wmMaterial.getUrl());
        //5.删除素材表数据
        this.removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancel(Integer id) {
        //TODO
        //1.判断参数的合法性
        if (id ==null ||id<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断数据是否存在
        /*WmMaterial byId = this.getById(id);
        if (byId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }*/
        Integer count = this.lambdaQuery().eq(WmMaterial::getId, id).count();
        if (count<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.执行更新
        this.lambdaUpdate().eq(WmMaterial::getId,id).set(WmMaterial::getIsCollection,0 ).update();
        //4.返回数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        //TODO
        //1.判断参数的合法性
        if (id ==null ||id<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断数据是否存在
        /*WmMaterial byId = this.getById(id);
        if (byId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }*/
        Integer count = this.lambdaQuery().eq(WmMaterial::getId, id).count();
        if (count<=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.执行更新
        this.lambdaUpdate().eq(WmMaterial::getId,id).set(WmMaterial::getIsCollection,1 ).update();
        //4.返回数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
